<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\User;
use app\admin\model\DistributeTask;
use app\admin\model\ShopPriceLog;
use app\admin\model\Shop as ShopModer;
use app\admin\model\ConfigData;
use think\Exception;
use think\Db;

class Shop extends Api
{
    protected $NeedLogin = []; //存在则不验证token

    public function _initialize(){
	    $action = request()->action();
	
		if(!in_array($action,$this->NeedLogin)){
			$ignore = array('host','accept','content-length','content-type');
			$headers = array();
			if($this->request->request('token')){
				$headers['token'] = $this->request->request('token');
			}else{
				foreach($_SERVER as $key=>$value){
					if(substr($key, 0, 5)==='HTTP_'){
						$key = substr($key, 5);
						$key = str_replace('_', ' ', $key);
						$key = str_replace(' ', '-', $key);
						$key = strtolower($key);
						if(!in_array($key, $ignore)){
							$headers[$key] = $value;
						}
					}
				}
			}
			$token=$headers['token'];
			if(strlen($token)!=32){
				$this->error('请登录');
			}
			$this->user=User::where(array('token'=>$token))->find();
			if(!$this->user){
				$this->error('请登录');
			}
			User::where(array('id'=>$this->user['id']))->update(array('active_time'=>time()));
		}
	}


    //新增商户
    public function add_shop(){
        $imgs = $this->request->request('imgs','');
        $name = $this->request->request('name','');
        $address = $this->request->request('address','');
        $industry = $this->request->request('industry','');

        if(!$name) $this->error('商家姓名错误');
        if(!$address) $this->error('地址错误');
        if(!$industry) $this->error('所属行业错误');
        if(!$imgs) $this->error('营业执照不可为空');

        $arr = [
            'name'=>$name,
            'imgs'=>$imgs,
            'industry'=>$industry,
            'address'=>$address,
            'add_time'=>time(),
            'user_id'=>$this->user['id']
        ];
        $info = ShopModer::where(['user_id'=>$this->user['id'],'status'=>['neq',-1]])->find();
        if($info){
            $this->error('请勿重复申请');
        }
        $res = ShopModer::insert($arr);

        if($res){
            $this->success('申请审核中');
        }else{
            $this->error('操作失败');
        }
    }

    //获取商户信息
    public function getShop(){
        $shop = ShopModer::where(['user_id'=>$this->user['id']])->find();
        if(!$shop){
            $this->error('操作错误');
        }

        $shop['nickname'] = $this->user['nickname'];

        $this->success('操作成功',$shop);
    }

    //获取余额资金明细
    public function get_shop_price_log(){
        $page = $this->request->request('page',1);
        $pagesize = $this->request->request('pagesize',10);
        $month = $this->request->request('month','');

        $shop = ShopModer::where(['user_id'=>$this->user['id']])->find();
        if(!$shop){
            $this->error('操作错误');
        }

        $start_time=strtotime($month.'-01');
		$end_time=strtotime($month.'-01 +1 month');
		$add_time=array('between',array($start_time,$end_time));
        $thismonth_1=strtotime(date("Y-m-01 00:00:01"));
		$thismonth_2=strtotime('+1 month',$thismonth_1);
        $thismonth=array('between',array($thismonth_1,$thismonth_2));
        $rose['yue']=$shop['balance'];
		$rose['month_in']=ShopPriceLog::where(array('user_id'=>$this->user['id'],'add_time'=>$thismonth,'price'=>['>',0]))->sum('price');	
		$rose['month_out']=0-ShopPriceLog::where(array('user_id'=>$this->user['id'],'add_time'=>$thismonth,'price'=>['<',0]))->sum('price');	
		$rose['month_log']=ShopPriceLog::where(array('user_id'=>$this->user['id'],'add_time'=>$add_time))->order('add_time desc')->limit(($page-1)*$pagesize,$pagesize)->select();
		foreach($rose['month_log'] as &$v){
			$v['add_time']=date("Y-m-d H:i:s",$v['add_time']);
            $v['status'] = 1;
            if($v['type'] == 1){
                if($v['is_freeze'] == 1){
                    $v['content'] = '余额冻结';
                }else{
                    $v['content'] = '余额支出';
                }
               
            }elseif($v['type'] == 2){
                $v['content'] = '余额充值';
            }elseif($v['type'] == 3){
                $v['content'] = '余额解冻';
            }
		}
        $this->success('操作成功',$rose);
    }


    //上传任务
    public function shop_add_task(){
        $id = $this->request->request('id','');
        $title = $this->request->request('title','');
        $content = $this->request->request('content','');
        $imgs = $this->request->request('imgs','');
        $shop = ShopModer::where(['user_id'=>$this->user['id']])->find();
        if(!$shop){
            $this->error('操作错误');
        }
        //查看用户账号余额
        if($shop['balance'] < $shop['task_unit_price'] && !$id){
            $this->error('账号余额不足');
        }
        Db::startTrans();
        try {
            $arr = [
                'add_time' => time(),
                'title'=>$title,
                'content'=>$content,
                'imgs'=> $imgs,
                'task_type'=>1,
                'type'=>$shop['name'],
                'category'=>$shop['name'],
                'character_type'=>1,
                'status'=>-3
            ];
            if($id){
                $res = DistributeTask::where(['id'=>$id])->update($arr);
            }else{
                $id = DistributeTask::insertGetId($arr);
                //冻结商户金额
                $arr = [
                    'user_id'=>$shop['user_id'],
                    'shop_id'=>$shop['id'],
                    'task_id'=>$id,
                    'is_freeze'=>1,
                    'price'=>$shop['task_unit_price']*-1,
                    'type'=>1,
                    'add_time'=>time()
                ];
                ShopPriceLog::insert($arr);
                //扣除用户账号金额
                $res = ShopModer::where(['id'=>$shop['id']])->update(['balance'=>$shop['balance']-$shop['task_unit_price']]);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if($res){
            $this->success('发布成功');
        }else{
            $this->error('发布失败');
        }
    }
    
    //获取我的任务列表
    public function getShopList(){
        $page = $this->request->request('page',1);
        $pagesize = $this->request->request('pagesize',10);
        $task_index = $this->request->request('task_index',1);  //1待审核   2待接单   3已接单  4已结算
        $shop = ShopModer::where(['user_id'=>$this->user['id']])->find();
        if(!$shop){
            $this->error('商家状态错误');
        }
        $where = [
            'type'=>$shop['name']
        ];
        if($task_index == 1){
            $where['status'] = -3;
        }elseif($task_index == 2){
            $where['status'] = 0;
        }elseif($task_index == 3){
            $where['status'] = ['in',[1,2,-1]];
        }elseif($task_index == 4){
            $where['status'] = 3;
        }

        $list = DistributeTask::where($where)->order('add_time desc')->limit(($page-1)*$pagesize,$pagesize)->select();
        foreach ($list as &$v) {
            $v['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
            $v['complete_time'] = date('Y-m-d H:i:s',$v['complete_time']);
            $v['receive_time'] = date('Y-m-d H:i:s',$v['receive_time']);

            if($v['status'] == -3){
                $v['statusName'] = '待审核';
            }elseif($v['status'] == -2){
                $v['statusName'] = '已退回';
            }elseif($v['status'] == 0){
                $v['statusName'] = '待接单';
            }elseif($v['status'] == 1 || $v['status'] == 2 || $v['status'] == -1){
                $v['statusName'] =  '已接单';
            }elseif($v['status'] == 3){
                $v['statusName'] = '已完成';
            }
        }
        
        $this->success('获取成功',$list);
    }

    //获取自己今日已发送
    public function send_task_sum(){
        $shop = ShopModer::where(['user_id'=>$this->user['id'],'status'=>1])->find();
        if($shop){
            $task_sum = DistributeTask::whereTime('receive_time', 'today')->where(['status'=>1,'type'=>$shop['name']])->count();
        }else{
            $task_sum = 0;
        }
        $this->success('操作成功',$task_sum);

    }
}